import OpenAI from 'openai';
import http from 'node:http'
import os from 'node:os';

const openai = new OpenAI({
  apiKey: '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', // defaults to process.env["OPENAI_API_KEY"]
});

const server = http.createServer(async (req, res) => {

  if (req.url !== "/favicon.ico" && req.url === '/chatgpt' && req.method == "POST") {
    console.log(req.url, req)

    res.writeHead(200, {
      "Content-Type": "application/octet-stream",
    });
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString(); // 将接收到的数据拼接起来  
    });
    req.on('end', async () => {
      if (body) {
        try {
          const stream = await openai.chat.completions.create({
            messages: [{ role: 'user', content: body }],
            model: 'gpt-3.5-turbo',
            stream: true,
          });
          for await (const part of stream) {
            console.log(`${part.choices[0]?.delta?.content || ''}`)
            //  res.write(`${part.choices[0]?.delta?.content || ''}`);
            // res.writeHead
          };
          res.end();
        } catch (err) {
          res.end(err.toString());
        }
      }
    });
    return;
  }

  if (req.url !== "/favicon.ico" && req.url === '/chatgpt' && req.method == "GET") {

    res.end(`
    <html>
    <head> <meta charSet="utf-8" /></head>
      <script type="text/javascript">
      window.onload=function(){
       
        const $submit=document.getElementById("submit")
        const $input=document.getElementById("input")
        $submit.addEventListener('click',()=>{
          request($input.value)
         })
      }
       function request(content){
    
       
       
        fetch('http://54.252.240.161/chatgpt',{
          method: 'POST',
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
          body:content
        })  
        .then(response => response.blob())  
        .then(blob => {  
          // 将二进制数据转换为可在浏览器中解析的HTML格式  
          const reader = new FileReader();  
          reader.onload = function(event) {  
            const htmlText = event.target.result;  
            // 在这里处理接收到的HTML数据  
            console.log(htmlText);  
          };  
          reader.readAsText(blob);  
        });
       }
      </script>
      <body>
        <input id="input" type="textarea"/>
        <button id="submit">发送</button/>
      </body>
    </html>
    `)
    return;
  }
  res.end(JSON.stringify({
    data: 'Not Found! 404',
  }));

});

server.listen(3000, () => {
  let networkInterfaces = os.networkInterfaces();
  let addresses = [];

  for (let k in networkInterfaces) {
    for (let k2 in networkInterfaces[k]) {
      let address = networkInterfaces[k][k2];
      if (address.family === 'IPv4' && !address.internal) {
        addresses.push(address.address);
      }
    }
  }
  console.log("server start:", `http://${addresses?.[0]}:3000`)
});

